package org.tio.sitexxx.im.server.handler;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.sitexxx.im.common.Command;
import org.tio.sitexxx.im.common.CommandHandler;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.ImSessionContext;
import org.tio.sitexxx.im.common.bs.P2PChatNtf;
import org.tio.sitexxx.im.common.bs.P2pQueryChatRecordReq;
import org.tio.sitexxx.im.common.utils.ImUtils;
import org.tio.sitexxx.im.server.Ims;
import org.tio.sitexxx.service.model.main.ChatRecordP2p;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.stat.ChatRecordP2PService;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.utils.json.Json;
import org.tio.utils.lock.ListWithLock;
import org.tio.utils.lock.ReadLockHandler;

/**
 * 获取p2p聊天记录数据-请求
 * @author tanyaowu
 */
@CommandHandler(Command.P2P_QUERY_CHAT_RECORD_REQ)
public class P2pQueryChatRecordReqHandler implements ImServerHandler {
	private static Logger log = LoggerFactory.getLogger(P2pQueryChatRecordReqHandler.class);

	public static final P2pQueryChatRecordReqHandler me = new P2pQueryChatRecordReqHandler();

	public P2pQueryChatRecordReqHandler() {
	}

	@SuppressWarnings("unused")
	@Override
	public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket) throws Exception {
		ImSessionContext imSessionContext = ImUtils.getImSessionContext(channelContext);

		SimpleUser curr = ImUtils.getSimpleUser(channelContext);
		if (curr == null) {
			return;
		}

		P2pQueryChatRecordReq queryP2pChatRecordReq = Json.toBean(packet.getBodyStr(), P2pQueryChatRecordReq.class);

		Integer otherUid = queryP2pChatRecordReq.getUid();

		User otherUser = UserService.ME.getById(otherUid);

		if (otherUser == null) {
			log.error("不能根据uid[{}]找不到用户", otherUid);
			return;
		}

		ListWithLock<ChatRecordP2p> listWithLock = ChatRecordP2PService.me.getLastP2pChat(queryP2pChatRecordReq.getUid(), curr.getI());
		if (listWithLock == null || listWithLock.size() == 0) {
			return;
		}

		P2PChatNtf.ChatItem[] chatItems = new P2PChatNtf.ChatItem[listWithLock.size()];
		listWithLock.handle(new ReadLockHandler<List<ChatRecordP2p>>() {

			@Override
			public void handler(List<ChatRecordP2p> list) {
				int i = list.size() - 1;
				for (ChatRecordP2p chatRecordP2p : list) {
					chatItems[i--] = P2PChatNtf.ChatItem.fromChatRecord(chatRecordP2p);
				}
			}
		});

		P2PChatNtf p2PChatNtf = new P2PChatNtf();
		p2PChatNtf.setTo(SimpleUser.fromUser(otherUser));
		p2PChatNtf.setFrom(curr);
		p2PChatNtf.setItems(chatItems);

		//		
		ImPacket respPacket = new ImPacket(Command.P2P_CHAT_NTY, p2PChatNtf);
		Ims.send(channelContext, respPacket);
	}

}
